// pages/goods-detail/goods-detail.js
var util = require("../../utils/util.js");

Page({

    /**
     * 页面的初始数据
     */
    data: {
        indicatorDots: true,
        vertical: false,
        autoplay: true,
        interval: 2000,
        duration: 500,
        productNum: '',
        isShowOptions: !1,
        isMoreTime: !1,
        couponId: 0,
        number: 1, //数量
        message: '',
        typeList: [], //产品类别
        distributionTimesList: [], //配送次数列表,
        distributionOrder: ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "多"],
        maxStock: 99,
        isSubmit: false //防止表单重新提交
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        const _this = this;
        _this.getGoodsDetail(options.productId);
        _this.setData({
            productId: options.productId,
            distributionTimes: ~~options.centerNum || 1, //弹窗里面选择配送的次数
            confirmDistributionTimes: ~~options.centerNum || 1, //外面是否单次配送判断变量
            productNum: ~~options.productNum || 1, //页面里的数值
            number: ~~options.productNum || 1 //弹窗里面的+-数值
        })
    },
    getGoodsDetail: function(e) {
        const _this = this;
        util.request(getApp().api.goods.detail, { productId: e }).then(
            function(res) {
                console.log(res);
                if (res.code == 200) {
                    let goods = res.data[0];
                    goods.sellPrice = goods.sellPrice / 100;
                    goods.trackFee = goods.trackFee / 100;
                    _this.setData({
                        goods: goods,
                        selectProp: { bottle: goods.bottle, productSpec: goods.productSpec },
                        chooseProp: { bottle: goods.bottle, productSpec: goods.productSpec },
                        selectWeight: goods.productHeft,
                        selectPrice: goods.sellPrice,
                        //单次配送价格
                        oncePrice: _this.oncePriceCalculationFormula(goods.sellPrice, _this.data.number, goods.productHeft / 1000),
                        moreUnitPrice: ~~goods.trackFee,
                        morePrice: _this.morePriceCalculationFormula(goods.sellPrice, _this.data.number, goods.productHeft / 1000, _this.data.distributionTimes, ~~goods.trackFee)
                    });

                    if (_this.data.maxStock < _this.data.number) {
                        _this.setData({
                            productNum: _this.data.maxStock, //页面里的数值
                            number: _this.data.maxStock //弹窗里面的+-数值
                        })
                    }
                } else {
                    wx.showToast({
                        title: res.msg, //提示的内容,
                        icon: "none", //图标,
                        //duration: 1500, //延迟时间,
                        mask: false, //显示透明蒙层，防止触摸穿透,
                    });
                    setTimeout(function() {
                        wx.hideToast();
                    }, 1500);
                }
            }
        );
    },
    //产品类别
    getTypeList: function(e) {
        let _this = this;
        util.request(getApp().api.goods.productTypeList).then(
            function(res) {
                console.log('产品类别', res);
                if (res.code == 200) {
                    _this.setData({
                        typeList: res.data
                    });
                } else {
                    wx.showToast({
                        title: res.msg, //提示的内容,
                        icon: "none", //图标,
                        //duration: 1500, //延迟时间,
                        mask: false, //显示透明蒙层，防止触摸穿透,
                    });
                    setTimeout(function() {
                        wx.hideToast();
                    }, 1500);
                }
            }
        );
    },
    //配送次数
    selectCenterNum: function(e) {
        let _this = this;
        util.request(getApp().api.goods.selectCenterNum, {
            productSpec: _this.data.chooseProp.productSpec,
            buyNum: _this.data.number,
            bottle: _this.data.chooseProp.bottle
        }).then(
            function(res) {
                if (res.code == 200) {
                    /*
                     * 如果配送次数是2次  返回 1,2
                     * 如果配送次数是5次  返回 1,3,5
                     * */
                    let tempTimesList = [1];
                    if (~~res.data >= 2) {
                        let start = (res.data % 2 === 1) ? 3 : 2;
                        for (let i = start; i <= res.data; i = i + 2) {
                            tempTimesList.push(i);
                        }
                        _this.setData({
                            distributionTimesList: tempTimesList
                        });
                    } else {
                        _this.setData({
                            distributionTimesList: tempTimesList
                        });
                    }
                } else {
                    wx.showToast({
                        title: res.msg, //提示的内容,
                        icon: "none", //图标,
                        mask: false, //显示透明蒙层，防止触摸穿透,
                    });
                    setTimeout(function() {
                        wx.hideToast();
                    }, 1500);
                }
            }
        );
    },
    //点击选择规格
    toChooseItem: function(e) {
        let _this = this;
        let productSpec = e.currentTarget.dataset.productSpec;
        let bottle = e.currentTarget.dataset.bottle;
        //重新设置选择后的属性(点击黑色背景取消的时候不能影响原来的selectProp)
        this.setData({
            chooseProp: { bottle: bottle, productSpec: productSpec }
        });
        util.request(getApp().api.goods.productTypeDetail, {
            productSpec: productSpec,
            bottle: bottle
        }).then(
            function(res) {
                if (res.code == 200) {
                    console.log(res.data);
                    _this.setData({
                        selectWeight: res.data[0].productHeft,
                        selectPrice: res.data[0].sellPrice / 100,
                        selectTrackFee: res.data[0].trackFee / 100,
                        distributionTimes: 1,
                        productId: res.data[0].id
                    });
                    //如果选择值 大于 最大购买数
                    if (_this.data.maxStock < _this.data.number) {
                        _this.setData({
                            productNum: _this.data.maxStock, //页面里的数值
                            number: _this.data.maxStock //弹窗里面的+-数值
                        })
                    }
                } else {
                    wx.showToast({
                        title: res.msg, //提示的内容,
                        icon: "none", //图标,
                        mask: false, //显示透明蒙层，防止触摸穿透,
                    });
                    setTimeout(function() {
                        wx.hideToast();
                    }, 1500);
                }
            }
        );
        //重新计算请求配送次数
        this.selectCenterNum();
    },
    //点击选择配送次数
    toChooseDistributionTimes: function(e) {
        let distributionTimes = e.currentTarget.dataset.distributionTimes;
        //重新设置选择后的属性
        this.setData({
            distributionTimes: distributionTimes
        });
    },
    //选择确认
    toConfirmChoose: function() {
        var _this = this;
        if (!_this.data.selectTrackFee) {
            _this.setData({
                selectTrackFee: _this.data.moreUnitPrice
            })
        }
        if (_this.data.number <= _this.data.maxStock) {
            _this.setData({
                selectProp: { bottle: _this.data.chooseProp.bottle, productSpec: _this.data.chooseProp.productSpec },
                productNum: _this.data.number,
                confirmDistributionTimes: _this.data.distributionTimes,
                oncePrice: _this.oncePriceCalculationFormula(_this.data.selectPrice, _this.data.number, _this.data.selectWeight / 1000),
                morePrice: _this.morePriceCalculationFormula(_this.data.selectPrice, _this.data.number, _this.data.selectWeight / 1000, _this.data.distributionTimes, _this.data.selectTrackFee)
            });
            setTimeout(function() {
                _this.setData({
                    isShowOptions: !1,
                })
            }, 200)
        } else {
            wx.showToast({
                title: '最多购买99箱', //提示的内容,
                icon: "none", //图标,
                mask: false, //显示透明蒙层，防止触摸穿透,
            });
            setTimeout(function() {
                wx.hideToast();
            }, 1500);
        }

    },
    //确认订单
    toOrder: function(e) {
        var _this = this;
        let times = ~~e.currentTarget.dataset.times;
        if (_this.data.number > _this.data.maxStock) {
            wx.showToast({
                title: '最多购买99箱', //提示的内容,
                icon: "none", //图标,
                mask: false, //显示透明蒙层，防止触摸穿透,
            });
            setTimeout(function() {
                wx.hideToast();
            }, 1500);
            return false;
        }
        if (_this.data.productNum < times) {
            wx.showToast({
                title: '送货' + times + '次,最少购买' + times + '箱', //提示的内容,
                icon: "none", //图标,
                mask: false, //显示透明蒙层，防止触摸穿透,
            });
            setTimeout(function() {
                wx.hideToast();
            }, 1500);
            return false;
        }
        const isLogin = wx.getStorageSync('openid');
        if (isLogin) {
            wx.setStorageSync("orderItem", JSON.stringify({
                productId: _this.data.productId, //产品ID
                productNum: _this.data.productNum, //产品数量
                bottle: _this.data.selectProp.bottle, //产品规格--多少瓶
                productSpec: _this.data.selectProp.productSpec, //产品规格--多少毫升
                selectWeight: ~~_this.data.selectWeight,
                finallyDistributionTimes: times, //产品送货几次
                trackFee: _this.data.selectTrackFee || 0,
                money: e.currentTarget.dataset.money
            }));
            wx.navigateTo({
                url: "/pages/order/order"
            })
        } else {
            _this.selectComponent('#login').openLoginModal();
        }

    },
    toCard: function() {
        wx.navigateTo({
            url: '/pages/card/card'
        })
    },
    //打开参数选择弹窗
    chooseOptions: function() {
        this.getTypeList();
        this.selectCenterNum();
        this.setData({
            isShowOptions: !0
        })
    },
    closeOptions: function() {
        this.setData({
            chooseProp: this.data.selectProp,
            distributionTimes: 1,
            isShowOptions: !1
        });
    },
    numberSub: function() {
        this.setData({
            number: (this.data.number - 1 > 1) ? this.data.number - 1 : 1,
            distributionTimes: 1
        });
        //重新计算请求配送次数
        this.selectCenterNum();
    },
    numberAdd: function() {
        this.setData({
            number: this.data.number + 1 <= this.data.maxStock ? this.data.number + 1 : this.data.maxStock,
            distributionTimes: 1
        });
        //重新计算请求配送次数
        this.selectCenterNum();
    },
    numberBlur: function(e) {
        var num = ~~e.detail.value;
        if (num <= 0) num = 1;
        if (this.data.maxStock && (num > this.data.maxStock)) num = this.data.maxStock;
        this.setData({ number: num, distributionTimes: 1 });
        //重新计算请求配送次数
        this.selectCenterNum();
    },
    /**
     * 单次价格配送计算公式 (虽然可以合并，以防需求变化 还是分开来写)
     */
    oncePriceCalculationFormula: function(basePrice, num, weight) {
        return basePrice * num
    },
    /**
     * 多次价格配送计算公式(虽然可以合并，以防需求变化 还是分开来写)
     */
    morePriceCalculationFormula: function(basePrice, num, weight, times, trackFee) {

        return basePrice * num + +(times - 1) * 50

    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function(res) {
        const openid = wx.getStorageSync('token');
        if (res.from === 'button') {}
        return {
            title: this.data.goods.productTitle,
            path: "/pages/goods-detail/goods-detail?productId=" + this.data.productId + '&productNum=' + this.data.productNum + '&openid=' + openid,
            success: function(res) {
                if (res.errMsg == 'shareAppMessage:ok') {}
            },
            fail: function() {
                if (res.errMsg == 'shareAppMessage:fail cancel') {} else if (res.errMsg == 'shareAppMessage:fail') {}
            },
            complete: function() {

            }
        }
    }

})